package com.sxpi.order.service.mq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022-09-10$ 15:12$
 */
@Component
@Slf4j
public class DeadOrderPublisher {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment evn;

    /**
     * 将用户下的订单ID发送给死信队列
     * @param orderId
     */
    public void sendMessage(Long orderId){
        try {
            // 设置消息的传输格式是JSON
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
            // 设置基本交换机
            rabbitTemplate.setExchange(evn.getProperty("mq.producer.order.exchange.name"));
            // 设置基本路由
            rabbitTemplate.setRoutingKey(evn.getProperty("mq.producer.order.routing.key.name"));
            // 设置发送对象类型消息
            rabbitTemplate.convertAndSend(orderId, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws AmqpException {
                    MessageProperties messageProperties = message.getMessageProperties();
                    // 设置消息持久化模式
                    messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    // 设置消息头，即直接指定发送消息所属的对象类型
                    messageProperties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME,Long.class);
                    // 返回消息
                    return message;
                }
            });

            log.info("【success】---->用户用户支付超时，发送用户下单记录id的消息入死信队列内容是：orderId:{}",orderId);
        }catch (Exception ex){
            log.error("【error】---->用户下单支付超时，发送用户下单记录id的消息如死信队列--发生异常:orderId:{}",orderId, ex.fillInStackTrace());
        }
    }
}
